import React, { useState, useEffect } from 'react'
import {
  ProFormColumnsType,
} from '@ant-design/pro-components';
import { ColumnType, TableProps } from 'antd/lib/table'
import { PaginationProps } from 'antd/lib/pagination'
import { Card, Pagination, Button, Table, Col, Row } from 'antd';
import useCacheAlive from '@/hooks/useCacheAlive';
import Form from './QueryForm'
import styles from './index.module.less'
import { RedoOutlined } from '@ant-design/icons';
import { isFunction, orderBy } from 'lodash';

type QueryFetchParams = {
  page: number,
  limit: number,
  offset: number,
  orderby: string,
  order: 0 | 1,
  [index:string]: any
}
type List = {
  data?: Array<any>
  total?: number
}

type Props = {
  name?: string,
  formColumns: ProFormColumnsType[],
  columns: TableProps['columns'],
  rowKey?: string,
  operator?: React.ReactNode,
  pageProps?: PaginationProps,
  rowSelectionProps?: TableProps['rowSelection'],
  getData: (data: QueryFetchParams) => Promise<List | undefined | false>
  hasSeletor?: boolean,
  hasPage?: boolean,
  hasOrder?: boolean,
  hasSearch?: boolean,
  hasReload?: boolean,
  onSelector?: (data: {keys: React.Key[], rows: any}) => void,
  refreshKey?: number | string | null,
}

const pageInit = {
  current: 1,
  pageSize: 10,
  total: 0
}

const MemoTable:React.FC<Props> = (props) => {
  const {hasOrder = true, hasPage = true, hasSeletor = false, hasSearch = true, hasReload = true, formColumns = []} = props
  const [formData, setFormData] = useCacheAlive({}, `table-form-${props.name}`)
  const [tableList, setTableList] = useCacheAlive([], `table-list-${props.name}`)
  const [page, setPage] = useCacheAlive({...pageInit}, `table-page-${props.name}`)
  const [order, setOrder] = useCacheAlive<any>({}, `table-order-${props.name}`)
  const [selector, setSelector] = useCacheAlive<any>({}, `table-selector-${props.name}`)
  const [col, setCol] = useState(null)
  const [width, setWidth] = useState(0)
  const [loading, setLoading] = useState(false)


  const onFormSubmit = (values: any) => {
    console.log(values,'')
    const p = {...page, current: 1}
    setSelector([])
    setFormData(values || {})
    setPage(p)
    fetchList(p, order, values)
  }

  const onChange = async (pagination, _, sorter) => {
    setSelector([])
    setPage(pagination)
    setOrder(sorter)
    fetchList(pagination, sorter, formData)
  
  }

  const fetchList = async (page, sort, search) => {
    const transfer: QueryFetchParams = {
      page: page.current,
      limit: page.pageSize,
      pageNum:page.current,
      pageSize:page.pageSize,
      offset: page.pageSize * (page.current - 1),
      orderby: sort.columnKey,
      order: sort.order === 'ascend' ? 0 : 1,
      ...search
    }
    if(isFunction(props.getData)) {
      setLoading(true)
      const data = await props.getData(transfer)
      if(data) {
        setTableList(data.data)
        setPage({...page, total: data.total})
        // reload()
      }
      setLoading(false)
    }
  }

  const onChangeRow = (selectedRowKeys: React.Key[], selectedRows: any) => {
    setSelector({selectedRowKeys, selectedRows})
    isFunction(props.onSelector)  && props.onSelector({keys: selectedRowKeys, rows: selectedRows})
  }

  const reload = () => {
    fetchList(page, order, formData)
  }

  useEffect(() => {
    console.log(props,'props')
    let w = hasSeletor ? 60 : 0
    const list: any = (props.columns || []).map(e => {
      const m = {...e} as ColumnType<any>
      w = w + (e.width as number || 200)
      if(order){
        if(m.dataIndex && m?.dataIndex === order?.columnKey) {
          m.defaultSortOrder = order.order
        }
      }
      return m
    })
    setCol(list)
    setWidth(w)
    isFunction(props.onSelector) && props.onSelector(selector)
    reload()

  }, [props.columns,props.refreshKey])
  
  const pagination:PaginationProps = {
    size: "small",
    pageSizeOptions: [10, 20, 50, 100],
    // position: ['bottomLeft'],
    ...props.pageProps,
    total: page.total,
    current: page.current,
    pageSize: page.pageSize
  }


  const rowSelection: TableProps['rowSelection'] = hasSeletor ? {
    type: 'checkbox',
    onChange: onChangeRow,
    defaultSelectedRowKeys: selector.selectedRowKeys,
    ...props.rowSelectionProps,
  } : null

  return (
    <div>
      {
        hasSearch && formColumns.length ? <Card className={styles.form || []}>
          <Form initialData={formData} columns={props.formColumns} onFinish={onFormSubmit}/>
        </Card> : null
      }
      <Card style={{marginTop:'2%'}}>
        <div className={styles.operator}>
          <Row justify='space-between' style={{marginBottom: '10px'}}>
            <Col flex='1'>{props.operator ? props.operator: null}</Col>
            <Col flex="60px" style={{textAlign: 'right'}}>{hasReload ? <div><Button onClick={reload} icon={<RedoOutlined />}></Button></div> : null}</Col>
          </Row>
        </div>
        {col ? <Table 
          loading={loading}
          bordered={true}
          scroll={{x: width,}}
          dataSource={tableList}
          columns={col} 
          onChange={onChange} 
          rowSelection={rowSelection}
          pagination={{
            size: "small",
            pageSizeOptions: [10, 20, 50, 100],
            position: ['bottomLeft'],
            ...props.pageProps,
            total: page.total,
            current: page.current,
            pageSize: page.pageSize
          }} 
          rowKey={props.rowKey} 
          /> : null }
      </Card>
    </div>
  )
}

export default MemoTable
